package com.onlinesshop.mall.controller;

import com.onlinesshop.mall.utils.CaptChaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**获取验证码
 * @author 叶建雄
 * @date 2019/12/23 12:06
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

    /**
     * random随机数 防止浏览器认为是同一个请求
     * 返回图片，并且将验证码字符串放入session中captchacode
     * @param response
     * @param request
     */
    @RequestMapping("/getcode")
    public void getCode(HttpServletResponse response,HttpServletRequest request){
        //获取图片验证码对象
        CaptChaUtil captChaUtil = new CaptChaUtil();
        captChaUtil.setHeight(36);
        captChaUtil.setWidth(40);
        captChaUtil.setVcodeLen(4);
        //获取随机验证码
        String captcha = captChaUtil.generatorVCode();
        //将验证码保存到session中
        request.getSession().setAttribute("captchacode",captcha);
        //生成验证码
        BufferedImage bufferedImage = captChaUtil.generatorRotateVCodeImage(captcha, false);
        try {
            ImageIO.write(bufferedImage,"png",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 判断用户输入的验证码是否正确
     * @param code  用户输入的验证码
     * @param model  用model保存信息
     * @param request
     * @return boolean
     */
    @RequestMapping("/judgecode")
    @ResponseBody
    public boolean judgeCode(@RequestParam(value = "code")String code, Model model, HttpServletRequest request){
        String captchacode = (String) request.getSession().getAttribute("captchacode");
        if (!captchacode.equals(code)){
            model.addAttribute("registermsg","验证码输入错误");
            return false;
        }
        return true;
    }

}
